package by.koleda.benicetobunnies.service;

import java.util.ArrayList;

import by.koleda.benicetobunnies.manager.CompaniesManager;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class SearchService extends Service {

	public static final String EXTRA_KEY_MESSAGE = "message";
	
	public static final String ACTION_ON_ERROR = "by.koleda.photoupdater.service.SEARCH_SERVICE_ACTION_ON_ERROR";
	
	public static final String ACTION_ON_SUCCESS = "by.koleda.photoupdater.service.SEARCH_SERVICE_ACTION_ON_SUCCESS";
		
	public static final String TAG = SearchService.class.getSimpleName();
	
	public static final String RESULT_TAG = "result";
	
	public static final String COMPANY_TAG = "company";
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		handleCommand(intent);
		return START_STICKY;
	}

	protected void handleCommand(Intent intent) {
		if (intent == null) {
			return;
		}

		final String companyName = intent.getStringExtra(COMPANY_TAG);

		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					int result = 0;
					if (!companyName.equals("")) {
						ArrayList<String> companiesList = CompaniesManager
								.getCompanies(SearchService.this);
						ArrayList<String> parentCompaniesList = CompaniesManager
								.getParentCompanies(SearchService.this);
						ArrayList<String> dictionary = CompaniesManager
								.createDictionary(companyName);
						for (String entry : dictionary) {
							if (companiesList.contains(entry)
									|| parentCompaniesList.contains(entry)) {
								result = 1;
								break;
							}
						}
						if (result != 1) {
							result = 2;
						}
					}
					Intent intent = new Intent(ACTION_ON_SUCCESS);
					intent.putExtra(RESULT_TAG, result);
					sendBroadcast(intent);
				} catch (Exception e) {
					Log.e(TAG, e.getMessage());
					Intent errorIntent = new Intent(ACTION_ON_ERROR);
					sendBroadcast(errorIntent);
				}
			}
		}).start();
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

}
